package com.example.taskmanager;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

public class TaskManager {

    public static void insertTask(String name, String description, String dueDate, String groupName) {
        String sql = "INSERT INTO tasks(name, description, status, due_date, group_name) VALUES(?,?,?,?,?)";

        try (Connection conn = DatabaseHelper.connect();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, name);
            pstmt.setString(2, description);
            pstmt.setString(3, "未完成"); // 默认状态为“未完成”
            pstmt.setString(4, dueDate);
            pstmt.setString(5, groupName);
            pstmt.executeUpdate();
            System.out.println("已插入新任务。");
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
    }

    public static List<Task> getAllTasks() {
        String sql = "SELECT id, name, description, status, due_date, group_name FROM tasks";
        return getTasksByQuery(sql);
    }

    public static List<Task> getIncompleteTasks() {
        String sql = "SELECT id, name, description, status, due_date, group_name FROM tasks WHERE status = '未完成'";
        return getTasksByQuery(sql);
    }

    public static List<Task> getCompletedTasks() {
        String sql = "SELECT id, name, description, status, due_date, group_name FROM tasks WHERE status = '完成'";
        return getTasksByQuery(sql);
    }

    public static List<Task> getTasksDueToday() {
        LocalDate today = LocalDate.now();
        String sql = "SELECT id, name, description, status, due_date, group_name FROM tasks WHERE due_date = ?";
        return getTasksByDateQuery(sql, today.toString());
    }

    public static List<Task> getTasksDueThisWeek() {
        LocalDate startOfWeek = LocalDate.now().with(java.time.temporal.TemporalAdjusters.previousOrSame(java.time.DayOfWeek.MONDAY));
        LocalDate endOfWeek = startOfWeek.plusDays(6);
        String sql = "SELECT id, name, description, status, due_date, group_name FROM tasks WHERE due_date BETWEEN ? AND ?";
        return getTasksByDateQuery(sql, startOfWeek.toString(), endOfWeek.toString());
    }

    public static List<Task> getTasksByGroupName(String groupName) {
        String sql = "SELECT id, name, description, status, due_date, group_name FROM tasks WHERE group_name = ?";
        return getTasksByQuery(sql, groupName);
    }

    public static List<String> getAllGroupNames() {
        List<String> groupNames = new ArrayList<>();
        String sql = "SELECT DISTINCT group_name FROM tasks";

        try (Connection conn = DatabaseHelper.connect();
             PreparedStatement pstmt = conn.prepareStatement(sql);
             ResultSet rs = pstmt.executeQuery()) {

            while (rs.next()) {
                groupNames.add(rs.getString("group_name"));
            }
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
        return groupNames;
    }

    private static List<Task> getTasksByQuery(String sql, String... params) {
        List<Task> tasks = new ArrayList<>();

        try (Connection conn = DatabaseHelper.connect();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            for (int i = 0; i < params.length; i++) {
                pstmt.setString(i + 1, params[i]);
            }

            try (ResultSet rs = pstmt.executeQuery()) {
                while (rs.next()) {
                    Task task = new Task(
                            rs.getInt("id"),
                            rs.getString("name"),
                            rs.getString("description"),
                            rs.getString("status"),
                            rs.getString("due_date"),
                            rs.getString("group_name")
                    );
                    tasks.add(task);
                }
            }
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
        return tasks;
    }

    private static List<Task> getTasksByDateQuery(String sql, String... params) {
        List<Task> tasks = new ArrayList<>();

        try (Connection conn = DatabaseHelper.connect();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            for (int i = 0; i < params.length; i++) {
                pstmt.setString(i + 1, params[i]);
            }

            try (ResultSet rs = pstmt.executeQuery()) {
                while (rs.next()) {
                    Task task = new Task(
                            rs.getInt("id"),
                            rs.getString("name"),
                            rs.getString("description"),
                            rs.getString("status"),
                            rs.getString("due_date"),
                            rs.getString("group_name")
                    );
                    tasks.add(task);
                }
            }
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
        return tasks;
    }

    public static void updateTaskStatus(int id, String newStatus) {
        String sql = "UPDATE tasks SET status = ? WHERE id = ?";

        try (Connection conn = DatabaseHelper.connect();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, newStatus);
            pstmt.setInt(2, id);
            pstmt.executeUpdate();
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
    }

    public static void deleteTask(int id) {
        String sql = "DELETE FROM tasks WHERE id = ?";

        try (Connection conn = DatabaseHelper.connect();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, id);
            pstmt.executeUpdate();
            System.out.println("任务已删除。");
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
    }
}
